module.exports = {
    skGet(sk, buf, fn = () => {}){
        let new_nuf = buf;

        if(sk.last_buf){
            new_nuf = Buffer.concat([sk.last_buf, buf], sk.last_buf.length + buf.length);
        }

        let offset = 0;
        while(true){
            let resize = this._read_buf_size(new_nuf, offset);
            let start_read_flg = offset + 2;
            let rd_len = start_read_flg + resize;
            if(resize && rd_len <= new_nuf.length){
                // 读取一个包
                const rd_buf = Buffer.alloc(resize);
                new_nuf.copy(rd_buf, 0, start_read_flg, rd_len);

                // buf 指针偏移到下一个内存区域
                offset = rd_len;

                // 回调业务数据
                fn(rd_buf);
            } else {
                const last_buf = Buffer.alloc(new_nuf.length - offset);
                new_nuf.copy(last_buf, 0, offset, new_nuf.length);

                sk.last_buf = last_buf;

                break;
            }
        }
    },
    skSend(buf){
        // tcp socket 打包发送的数据，非业务层
        const fst_buf = Buffer.alloc(2);
        fst_buf.writeInt16LE(buf.length);

        buf = Buffer(buf);

        return Buffer.concat([fst_buf, buf], fst_buf.length + buf.length);

    },
    _read_buf_size(buf, offset){
        let rt = 0;

        1 < buf.length - offset && (rt = buf.readInt16LE())

        return rt;
    }
};